package znet

import (
	"errors"
	logging "github.com/sirupsen/logrus"
	"sync"
	"webdemo/src/zinx/zinterface"
)

type ConnManager struct {
	connections map[uint32]zinterface.IConnection
	connLock    sync.RWMutex
}

func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]zinterface.IConnection),
	}
}

func (c *ConnManager) Add(conn zinterface.IConnection) {
	c.connLock.Lock()
	defer c.connLock.Unlock()
	c.connections[conn.GetConnID()] = conn
	logging.Info("[ConnManager][Add]connManager conn len is ", c.Len())
}

func (c *ConnManager) Remove(conn zinterface.IConnection) {
	c.connLock.Lock()
	defer c.connLock.Unlock()
	delete(c.connections, conn.GetConnID())
	logging.Info("[ConnManager][Remove]connManager conn len is ", c.Len())

}

func (c *ConnManager) GetConn(id uint32) (zinterface.IConnection, error) {
	c.connLock.RLock()
	defer c.connLock.RUnlock()

	if connection, ok := c.connections[id]; ok {
		return connection, nil
	}
	return nil, errors.New("connection not found")
}

func (c *ConnManager) Len() int {
	return len(c.connections)
}

func (c *ConnManager) ClearConn() {
	c.connLock.Lock()
	defer c.connLock.Unlock()
	for connId, conn := range c.connections {
		conn.Stop()
		delete(c.connections, connId)
	}
	logging.Info("[ConnManager][ClearConn]connManager conn len is ", c.Len())

}
